package com.chensi.admin.userservice.controller;

import com.google.gson.Gson;
import com.chensi.admin.userservice.common.BaseErrorCode;
import com.chensi.admin.userservice.common.Constants;
import com.chensi.admin.userservice.common.JsonResult;
import com.chensi.admin.userservice.feign.CommonService;
import com.chensi.admin.userservice.utils.CommonUtil;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author si.chen
 * @date 2019/6/2411:00
 */
@RestController
@Log4j2
public class UserCommonController {

    private final CommonService commonService;

    @Value("${upload.rootDir}")
    private String rootPath;

    @Value("${upload.uploadDir}")
    private String uploadFiles;

    @Autowired
    public UserCommonController(CommonService commonService) {
        this.commonService = commonService;
    }

    @GetMapping("/web/common/weatherForecast")
    public ResponseEntity<JsonResult> getWeather() {
        ResponseEntity<Object> jsonResult = commonService.getWeather();
        JSONObject result = JSONObject.fromObject(jsonResult.getBody());
        int httpCode = jsonResult.getStatusCode().value();
        if (Constants.HTTP_CODE == httpCode && result.get(Constants.code).equals(Constants.CODE)) {
            return ResponseEntity.ok(JsonResult.ok(result.get(Constants.data)));
        }
        return ResponseEntity.ok(JsonResult.failed(BaseErrorCode.UNKNOWN_EXCEPTION.getCode(), BaseErrorCode.UNKNOWN_EXCEPTION.getMessage()));
    }

    /**
     * 上传（兼容所有浏览器）
     * 注意:前端上传参数必须要携带filename
     *
     * @param request  请求体
     * @param response 响应体
     */
    @PostMapping("upload")
    public void upload(HttpServletRequest request, HttpServletResponse response) {

        // 防止乱码
        response.setContentType("application/json;charset=UTF-8");
        try {
            if (!(request instanceof MultipartHttpServletRequest)) {
                printHtml(response, JsonResult.failed(BaseErrorCode.FILE_NOT_EXIST.getCode(),
                        BaseErrorCode.FILE_NOT_EXIST.getMessage(), "没有文件"));
            }
            assert request instanceof MultipartHttpServletRequest;
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String relativePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            String ctxPath = rootPath + File.separator + uploadFiles;
            File dir = new File(ctxPath);
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    printHtml(response, JsonResult.failed(BaseErrorCode.UPLOAD_ERROR.getCode(),
                            BaseErrorCode.UPLOAD_ERROR.getMessage(), "上传失败"));
                }
            }
            String fileName;
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件名 //
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                if (StringUtils.isBlank(fileName)) {
                    continue;
                }
                String format = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
                fileName = "" + System.currentTimeMillis() + CommonUtil.getRandomNum(6);
                File uploadFile = new File(ctxPath + "/" + fileName + format);
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                sb.append(relativePath).append("/").append(fileName).append(format).append(",");
            }
            if (StringUtils.isBlank(sb.toString())) {
                printHtml(response, JsonResult.failed(BaseErrorCode.FILE_NOT_EXIST.getCode(),
                        BaseErrorCode.FILE_NOT_EXIST.getMessage(), "没有文件"));
            }
            String result = sb.deleteCharAt(sb.lastIndexOf(",")).toString();
            log.info("文件上传成功： " + result);
            printHtml(response, JsonResult.ok(result));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("************上传文件失败************");
            try {
                printHtml(response, JsonResult.failed(BaseErrorCode.UPLOAD_ERROR.getCode(),
                        BaseErrorCode.UPLOAD_ERROR.getMessage(), "上传失败"));
            } catch (IOException e1) {
                log.error("************上传文件失败************");
                e1.printStackTrace();
            }
        }

    }

    private void printHtml(HttpServletResponse response, Object msg) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(new Gson().toJson(msg));
        writer.close();
    }
}
